package com.tudouji.project.mt.service.impl;

import com.meituan.sdk.MeituanClient;
import com.meituan.sdk.MeituanRequest;
import com.meituan.sdk.MeituanResponse;
import com.meituan.sdk.annotations.ApiMeta;
import com.meituan.sdk.domain.ApiMetaInfo;
import com.meituan.sdk.internal.constants.CommonConstants;
import com.meituan.sdk.internal.exceptions.MtSdkException;
import com.meituan.sdk.internal.utils.AnnotationUtil;
import com.meituan.sdk.internal.utils.JsonUtil;
import com.meituan.sdk.internal.utils.SignerUtil;
import com.tudouji.common.exception.CustomException;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.framework.config.MTConfig;
import com.tudouji.project.mt.domain.*;
import com.tudouji.project.mt.http.CustomMeituanClient;
import com.tudouji.project.mt.http.request.*;
import com.tudouji.project.mt.http.response.*;
import com.tudouji.project.mt.http.token.AppAuthTokenUtils;
import com.tudouji.project.mt.service.IMtSalesService;
import com.tudouji.project.mt.service.IMtShopService;
import com.tudouji.project.mt.service.IMtTokenService;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.service.impl.SysDeptServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * 接口为分页时，多次获取其所有数据，页大小设置为200
 */
@Slf4j
@Service
public class MtPullService {

    @Autowired
    private MTConfig mtConfig;

    @Autowired
    private MtWhinServiceImpl mtWhinService;
    @Autowired
    private MtWhinitemServiceImpl mtWhinitemService;
    @Autowired
    private MtWhoutServiceImpl mtWhoutService;
    @Autowired
    private MtFoodconsumServiceImpl mtFoodconsumService;
    @Autowired
    private MtWhoutitemServiceImpl mtWhoutitemService;
    @Autowired
    private MtFoodconsumitemServiceImpl mtFoodconsumitemService;
    @Autowired
    private MtFoodconsumgoodsitemServiceImpl mtFoodconsumgoodsitemService;
    @Autowired
    private SysDeptServiceImpl sysDeptService;
    @Autowired
    private IMtTokenService iMtTokenService;
    @Autowired
    private IMtShopService iMtShopService;
    @Autowired
    private IMtSalesService iMtSalesService;

    //拼装授权URL
    public String authURL() {
        try {
            return AppAuthTokenUtils.completeAUTHURL();
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    //授权
    @Transactional
    public void auth(String code, String sign) {
        try {
            //保存授权码
            log.info("授权码：" + code);
            MtToken mtToken = new MtToken();
            mtToken.setAuthorizationCode(code);
            mtToken.setSign(sign);
            //授权：获取access_token(即appAuthToken)
            log.info("授权start：");
            //使用authorization_code换取access_token(即appAuthToken)
            CustomMeituanClient meituanClient = mtConfig.getInstanceClient();
            Map<String, String> queryMap = new HashMap<>();
            queryMap.put(CommonConstants.BUSINESS_ID, String.valueOf(18));
            queryMap.put(CommonConstants.CHARSET, "UTF-8");
            queryMap.put("code", mtToken.getAuthorizationCode());
            queryMap.put(CommonConstants.DEVELOPER_ID, MTConfig.getDeveloperId().toString());
            queryMap.put("grantType", "authorization_code");
            queryMap.put(CommonConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
            queryMap.put(CommonConstants.SIGN, SignerUtil.getSign(MTConfig.getSignKey(), queryMap));
            String responseStr = meituanClient.executeT(CommonConstants.SERVER_URL_PROD + "/oauth/token", queryMap, 18, null, String.valueOf(queryMap.get(CommonConstants.TIMESTAMP)));
            log.info("返回：" + responseStr.toString());
            AppAuthTokenResponse response = JsonUtil.fromJson(responseStr, AppAuthTokenResponse.class);
            if (response.getCode().equalsIgnoreCase("0")) {
                AppAuthTokenResponse.Response resp = response.getData();
                mtToken.setAccesstoken(resp.getAccessToken());
                mtToken.setExpirein(resp.getExpireIn());
                mtToken.setRefreshtoken(resp.getRefreshToken());
                mtToken.setScope(resp.getScope());
                mtToken.setOpbizcode(resp.getOpBizCode());
                iMtTokenService.insertMtToken(mtToken);
                log.info("授权end：" + resp);
            } else {
                log.info("调用失败");
            }
            //保存access_token
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    /**
     * 查询授权资源ID列表
     */
    @Transactional
    public void authResources() {
        try {
            MtToken mtToken = iMtTokenService.getLastTokenByConditions(new MtToken());
            log.info("获取授权：" + mtToken.toString());

            MeituanClient meituanClient = mtConfig.getInstanceClient();
            AuthResourcesRequest request = new AuthResourcesRequest();
            request.setDevId(MTConfig.getDeveloperId().intValue());
//            request.setBizAccId(mtToken.getOpbizcode());
            request.setBizId("18");
            MeituanResponse<AuthResourcesResponse> response = meituanClient.invokeApi(request, mtToken.getAccesstoken());
            if (response.isSuccess()) {
                AuthResourcesResponse resp = response.getData();
                for (int i = 0; i < resp.getResources().size(); i++) {
                    log.info(resp.getResources().get(i).toString());
                    MtShop mtShop = new MtShop();
                    mtShop.setMtOrgid(Long.valueOf(resp.getResources().get(i).getOrgId()));
                    List<MtShop> mtShopList = iMtShopService.selectMtShopList(mtShop);
                    if (mtShopList.size() == 0) {
                        mtShop.setCode(resp.getResources().get(i).getMerchantNo());
                        mtShop.setName(resp.getResources().get(i).getOrgName());
                        iMtShopService.insertMtShop(mtShop);
                    } else {
                        mtShop.setId(mtShopList.get(0).getId());
                        mtShop.setCode(resp.getResources().get(i).getMerchantNo());
                        mtShop.setName(resp.getResources().get(i).getOrgName());
                        iMtShopService.updateMtShop(mtShop);
                    }
                }

            } else {
                log.info("调用失败");
            }
            //保存access_token
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    /**
     * 授权刷新
     * 开放平台对访问令牌的过期时间默认设置为30天，如ISV/开发者的访问令牌过期未换，调用API的请求将被平台拒绝。
     * 更新令牌有效期为35天，更新令牌过期需要重新授权。
     */
    @Transactional
    public void authRefresh() {
        try {
            //保存授权码
            MtToken mtToken = iMtTokenService.getLastTokenByConditions(new MtToken());
            //授权：获取access_token(即appAuthToken)
            log.info("刷新授权start：");
            //使用authorization_code换取access_token(即appAuthToken)
            CustomMeituanClient meituanClient = mtConfig.getInstanceClient();
            Map<String, String> queryMap = new HashMap<>();
            queryMap.put(CommonConstants.TIMESTAMP, String.valueOf(System.currentTimeMillis() / 1000));
            queryMap.put("scope", "all");
            queryMap.put("refreshToken", mtToken.getRefreshtoken());
            queryMap.put("grantType", "refresh_token");
            queryMap.put(CommonConstants.DEVELOPER_ID, MTConfig.getDeveloperId().toString());
            queryMap.put(CommonConstants.CHARSET, "UTF-8");
            queryMap.put(CommonConstants.BUSINESS_ID, "18");
            queryMap.put(CommonConstants.SIGN, SignerUtil.getSign(MTConfig.getSignKey(), queryMap));
            String responseStr = meituanClient.executeT(CommonConstants.SERVER_URL_PROD + "/oauth/refresh", queryMap, 18, null, String.valueOf(queryMap.get(CommonConstants.TIMESTAMP)));
            log.info("返回：" + responseStr.toString());
            AppAuthTokenResponse response = JsonUtil.fromJson(responseStr, AppAuthTokenResponse.class);
            if (response.getCode().equalsIgnoreCase("0")) {
                AppAuthTokenResponse.Response resp = response.getData();
                mtToken.setAccesstoken(resp.getAccessToken());
                mtToken.setExpirein(resp.getExpireIn());
                mtToken.setRefreshtoken(resp.getRefreshToken());
                mtToken.setScope(resp.getScope());
                mtToken.setOpbizcode(resp.getOpBizCode());
                mtToken.setSign(queryMap.get(CommonConstants.SIGN));
                iMtTokenService.insertMtToken(mtToken);
                log.info("刷新授权end：" + resp);
            } else {
                log.info("调用失败");
            }
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    /**
     * 修改元素注解属性值
     *
     * @param element         被注解元素
     * @param annotationClass 注解类
     * @param key             注解属性key
     * @param value           注解属性value
     */
    public static void modifyAnnotationAttributeValue(AnnotatedElement element,
                                                      Class<? extends Annotation> annotationClass,
                                                      String key, Object value) throws NoSuchFieldException, IllegalAccessException {
        Annotation annotationToBeModified = element.getAnnotation(annotationClass);
        if (annotationToBeModified == null) return;

        InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotationToBeModified);
        Field memberValuesField = invocationHandler.getClass().getDeclaredField("memberValues");
        memberValuesField.setAccessible(true);
        Map<String, Object> memberValues = (Map<String, Object>) memberValuesField.get(invocationHandler);
        memberValues.put(key, value);
    }

    //入库主表
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void getWhin(MtShop shop, Long timeBegin, Long timeEnd, MtToken mtToken) throws Exception {
        Integer pageNo = 1;
        Integer pageSize = 200;
        HashMap<String, Long> snIdList = new HashMap<>();//保存出库单id与美团出库单主表编号的对应关系，获取明细时需要写入

        MeituanClient meituanClient = mtConfig.getInstanceClient();

        PoiStockInItemRequest scmChainQueryStockInItemRequest = new PoiStockInItemRequest();
        scmChainQueryStockInItemRequest.setOrgId(shop.getMtOrgid());
        scmChainQueryStockInItemRequest.setBizTimeBegin(timeBegin);
        scmChainQueryStockInItemRequest.setBizTimeEnd(timeEnd);
        scmChainQueryStockInItemRequest.setStatus(2);
        scmChainQueryStockInItemRequest.setPage(new PoiStockInItemRequest.Page(pageNo, pageSize));
        if (shop.getCode().startsWith("PSZX")){
            modifyAnnotationAttributeValue(scmChainQueryStockInItemRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/chain/stockInItem/query");
        }else{
            modifyAnnotationAttributeValue(scmChainQueryStockInItemRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/poi/stockInItem/query");
        }

        MeituanResponse<PoiStockInItemResponse> response = meituanClient.invokeApi(scmChainQueryStockInItemRequest, mtToken.getAccesstoken());
        log.info("response: " + response.toString());
        if (response.isSuccess()) {
            PoiStockInItemResponse resp = response.getData();

            //插入数据
            for (PoiStockInItemResponse.Whin whin : resp.getItems()) {
                MtWhin mtWhin = new MtWhin();
                mtWhin.setItemsn(whin.getItemSn());
                List<MtWhin> mtWhinList = mtWhinService.selectMtWhinList(mtWhin);
                if (mtWhinList.size() > 0) continue;

                mtWhin.setMtShopld(shop.getId());
                mtWhin.setMtOrgid(shop.getMtOrgid());
                mtWhin.setMtBelongsorgid(Long.valueOf(whin.getBelongOrg().getOrgId()));
                mtWhin.setMtRootorgid(Long.valueOf(whin.getRootOrgId()));
                mtWhin.setOrgId(shop.getOrgId());
                mtWhin.setOrgName(shop.getOrgName());
                if (null != whin.getWarehouse()) {
                    mtWhin.setMtWhCode(whin.getWarehouse().getCode());
                }
                mtWhin.setOppositeorgType(whin.getOppositeOrg().getType().getId());
                mtWhin.setOppositeorgName(whin.getOppositeOrg().getName());
                mtWhin.setOppositeorgCode(whin.getOppositeOrg().getCode());
                mtWhin.setBiztime(Long.valueOf(whin.getBizTime()));
                mtWhin.setMtStatus(whin.getStatus().getId());
                mtWhin.setType(whin.getType().getId());
                mtWhin.setSourcesn(whin.getSourceSn());
                mtWhin.setMtCreatedtime(Long.valueOf(whin.getCreatedTime()));
                mtWhin.setStockmoney(new BigDecimal(whin.getStockMoney()));
                mtWhin.setMoney(new BigDecimal(whin.getMoney()));
                mtWhin.setTax(new BigDecimal(whin.getTax()));
                mtWhin.setNotaxmoney(new BigDecimal(whin.getNoTaxMoney()));
                mtWhin.setModifytime(Long.valueOf(whin.getModifyTime()));
                mtWhin.setVersion(whin.getVersion());
                if (null != whin.getThirdRelatedSn()) {
                    mtWhin.setThirdrelatedsn(whin.getThirdRelatedSn());
                }
                SysDept sysDept = sysDeptService.selectDeptById(shop.getDeptId());
                mtWhin.setDepartmentguid(sysDept.getGuid());
                mtWhin.setStatus(1);
                mtWhin.setCreateBy(shop.getSysuserid());
                mtWhinService.insertMtWhin(mtWhin);

                snIdList.put(mtWhin.getItemsn(), mtWhin.getId());
            }
            //明细处理
            if (!snIdList.isEmpty()) {
                getWhinItem(shop, mtToken, snIdList);
                snIdList.clear();
            }

            //分页未查询完，继续查询
            if (resp.getPage().getTotalPageSize() - pageNo > 0) {
                pageNo++;
                this.getWhin(shop, timeBegin, timeEnd, mtToken);
            }
        } else {
            log.info("调用失败");
        }
    }

    //出库主表
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void getWhout(MtShop shop, Long timeBegin, Long timeEnd, MtToken mtToken) throws Exception {
        Integer pageNo = 1;
        Integer pageSize = 200;
        HashMap<String, Long> snIdList = new HashMap<>();//保存出库单id与美团出库单主表编号的对应关系，获取明细时需要写入

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        PoiStockOutItemRequest poiStockOutItemRequest = new PoiStockOutItemRequest();
        poiStockOutItemRequest.setOrgId(shop.getMtOrgid());
        poiStockOutItemRequest.setBizTimeBegin(timeBegin);
        poiStockOutItemRequest.setBizTimeEnd(timeEnd);
        poiStockOutItemRequest.setStatus(2);
        poiStockOutItemRequest.setPage(new PoiStockOutItemRequest.Page(pageNo, pageSize));
        if (shop.getCode().startsWith("PSZX")){
            modifyAnnotationAttributeValue(poiStockOutItemRequest.getClass(), ApiMeta.class, "path",
                    "/rms/scmplus/inventory/api/v1/chain/stockOutItem/query");
        }else{
            modifyAnnotationAttributeValue(poiStockOutItemRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/poi/stockOutItem/query");
        }

        MeituanResponse<PoiStockOutItemResponse> response = meituanClient.invokeApi(poiStockOutItemRequest, mtToken.getAccesstoken());
        log.info("response: " + response.toString());
        if (response.isSuccess()) {
            PoiStockOutItemResponse resp = response.getData();

            //插入数据
            for (PoiStockOutItemResponse.Whout whout : resp.getItems()) {
                MtWhout mtWhout = new MtWhout();
                mtWhout.setItemsn(whout.getItemSn());
                List<MtWhout> mtWhoutList = mtWhoutService.selectMtWhoutList(mtWhout);
                if (mtWhoutList.size() > 0) continue;

                mtWhout.setMtShopld(shop.getId());
                mtWhout.setMtOrgid(shop.getMtOrgid());
                mtWhout.setMtBelongsorgid(Long.valueOf(whout.getBelongOrg().getOrgId()));
                mtWhout.setMtRootorgid(Long.valueOf(whout.getRootOrgId()));
                mtWhout.setOrgId(shop.getOrgId());
                mtWhout.setOrgName(shop.getOrgName());
                if (null != whout.getWarehouse()) {
                    mtWhout.setMtWhCode(whout.getWarehouse().getCode());
                }

                if (whout.getOppositeOrg() != null) {
                    mtWhout.setOppositeorgType(whout.getOppositeOrg().getType().getId());
                    mtWhout.setOppositeorgName(whout.getOppositeOrg().getName());
                    mtWhout.setOppositeorgCode(whout.getOppositeOrg().getCode());
                }
                mtWhout.setBiztime(Long.valueOf(whout.getBizTime()));
                mtWhout.setMtStatus(whout.getStatus().getId());
                mtWhout.setType(whout.getType().getId());
                mtWhout.setSourcesn(whout.getSourceSn());
                mtWhout.setMtCreatedtime(Long.valueOf(whout.getCreatedTime()));
                mtWhout.setStockmoney(new BigDecimal(whout.getStockMoney()));
                mtWhout.setMoney(new BigDecimal(whout.getMoney()));
                mtWhout.setTax(new BigDecimal(whout.getTax()));
                mtWhout.setNotaxmoney(new BigDecimal(whout.getNoTaxMoney()));
                mtWhout.setModifytime(Long.valueOf(whout.getModifyTime()));
                mtWhout.setVersion(whout.getVersion());
                if (null != whout.getThirdRelatedSn()) {
                    mtWhout.setThirdrelatedsn(whout.getThirdRelatedSn());
                }
                SysDept sysDept = sysDeptService.selectDeptById(shop.getDeptId());
                mtWhout.setDepartmentguid(sysDept.getGuid());
                mtWhout.setStatus(1);
                mtWhout.setCreateBy(shop.getSysuserid());
                mtWhoutService.insertMtWhout(mtWhout);

                snIdList.put(whout.getItemSn(), mtWhout.getId());
            }
            //明细处理
            if (!snIdList.isEmpty()) {
                getWhoutItem(shop, mtToken, snIdList);
                snIdList.clear();
            }

            //分页未查询完，继续查询
            if (resp.getPage().getTotalPageSize() - pageNo > 0) {
                pageNo++;
                this.getWhout(shop, timeBegin, timeEnd, mtToken);
            }
        } else {
            log.info("调用失败");
        }
    }

    /**
     * 出库明细
     *
     * @param itemSns 单据号列表
     */
    public void getWhinItem(MtShop shop, MtToken mtToken, HashMap<String, Long> itemSns) throws Exception {

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        PoiStockInListRequest poiStockInListRequest = new PoiStockInListRequest();
        poiStockInListRequest.setOrgId(shop.getMtOrgid());
        String[] strings = itemSns.keySet().toArray(new String[itemSns.size()]);
        ArrayList<String> arrayList = new ArrayList();
        for (int i = 0; i < strings.length; i++) {
            arrayList.add(strings[i]);
        }
        poiStockInListRequest.setItemSns(arrayList);
        if (shop.getCode().startsWith("PSZX")){
            modifyAnnotationAttributeValue(poiStockInListRequest.getClass(), ApiMeta.class, "path",
                    "/rms/scmplus/inventory/api/v1/chain/stockIn/list");
        }else{
            modifyAnnotationAttributeValue(poiStockInListRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/poi/stockIn/list");
        }


        try {
            MeituanResponse<PoiStockInListResponse> response = meituanClient.invokeApi(poiStockInListRequest, mtToken.getAccesstoken());
            log.info("response: " + response.toString());
            if (response.isSuccess()) {
                PoiStockInListResponse resp = response.getData();

                //插入数据
                for (PoiStockInListResponse.WhinList whout : resp.getItems()) {

                    PoiStockInListResponse.WhinList.ItemBean itemBean = whout.getItem();
                    List<PoiStockInListResponse.WhinList.DetailsBean> detailsBeans = whout.getDetails();

                    Long mtWhinId = itemSns.get(itemBean.getItemSn());
                    for (int i = 0; i < detailsBeans.size(); i++) {
                        PoiStockInListResponse.WhinList.DetailsBean detailsBean = detailsBeans.get(i);
                        MtWhinitem mtWhinitem = new MtWhinitem();
                        mtWhinitem.setMtWhinid(mtWhinId);
                        if (null != detailsBean.getWarehouse()) {
                            mtWhinitem.setMtWhCode(detailsBean.getWarehouse().getCode());
                        }
                        mtWhinitem.setGoodsCode(detailsBean.getGoods().getCode());
                        mtWhinitem.setGoodsName(detailsBean.getGoods().getName());
                        mtWhinitem.setBaseunitId(detailsBean.getGoods().getBaseUnit().getId());
                        mtWhinitem.setBaseunitName(detailsBean.getGoods().getBaseUnit().getName());
                        mtWhinitem.setBizunit(detailsBean.getBizUnit());
                        mtWhinitem.setAmount(new BigDecimal(detailsBean.getAmount()));
                        mtWhinitem.setPrice(new BigDecimal(detailsBean.getPrice()));
                        mtWhinitem.setMoney(new BigDecimal(detailsBean.getMoney()));
                        mtWhinitem.setTaxrate(new BigDecimal(detailsBean.getTaxRate()));
                        mtWhinitem.setNotaxprice(new BigDecimal(detailsBean.getNoTaxPrice()));
                        mtWhinitem.setNotaxmoney(new BigDecimal(detailsBean.getNoTaxMoney()));
                        mtWhinitem.setTax(new BigDecimal(detailsBean.getTax()));
                        mtWhinitem.setStockprice(new BigDecimal(detailsBean.getStockPrice()));
                        mtWhinitem.setStockmoney(new BigDecimal(detailsBean.getStockMoney()));
                        mtWhinitem.setBizunitamount(new BigDecimal(detailsBean.getBizUnitAmount()));
                        mtWhinitem.setBizunitprice(new BigDecimal(detailsBean.getBizUnitPrice()));
                        mtWhinitem.setBizunitnotaxprice(new BigDecimal(detailsBean.getBizUnitNoTaxPrice()));
                        mtWhinitem.setBizunitstockprice(new BigDecimal(detailsBean.getBizUnitStockPrice()));
                        mtWhinitem.setStatus(1);
                        mtWhinitemService.insertMtWhinitem(mtWhinitem);
                    }
                }
            } else {
                log.info("调用失败");
            }
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    /**
     * 出库明细
     *
     * @param itemSns 单据号列表
     */
    public void getWhoutItem(MtShop shop, MtToken mtToken, HashMap<String, Long> itemSns) throws Exception {

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        PoiStockOutListRequest poiStockOutListRequest = new PoiStockOutListRequest();
        poiStockOutListRequest.setOrgId(shop.getMtOrgid());
        String[] strings = itemSns.keySet().toArray(new String[itemSns.size()]);
        ArrayList<String> arrayList = new ArrayList();
        for (int i = 0; i < strings.length; i++) {
            arrayList.add(strings[i]);
        }
        poiStockOutListRequest.setItemSns(arrayList);
        if (shop.getCode().startsWith("PSZX")){
            modifyAnnotationAttributeValue(poiStockOutListRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/chain/stockOut/list");
        }else{
            modifyAnnotationAttributeValue(poiStockOutListRequest.getClass(), ApiMeta.class,
                    "path", "/rms/scmplus/inventory/api/v1/poi/stockOut/list");
        }


        try {
            MeituanResponse<PoiStockOutListResponse> response = meituanClient.invokeApi(poiStockOutListRequest, mtToken.getAccesstoken());
            log.info("response: " + response.toString());
            if (response.isSuccess()) {
                PoiStockOutListResponse resp = response.getData();

                //插入数据
                for (PoiStockOutListResponse.WhoutList whout : resp.getItems()) {

                    PoiStockOutListResponse.WhoutList.ItemBean itemBean = whout.getItem();
                    List<PoiStockOutListResponse.WhoutList.DetailsBean> detailsBeans = whout.getDetails();

                    Long mtWhoutId = itemSns.get(itemBean.getItemSn());
                    for (int i = 0; i < detailsBeans.size(); i++) {
                        PoiStockOutListResponse.WhoutList.DetailsBean detailsBean = detailsBeans.get(i);
                        MtWhoutitem mtWhoutitem = new MtWhoutitem();
                        mtWhoutitem.setMtWhoutid(mtWhoutId);
                        if (null != detailsBean.getWarehouse()) {
                            mtWhoutitem.setMtWhCode(detailsBean.getWarehouse().getCode());
                        }
                        mtWhoutitem.setGoodsCode(detailsBean.getGoods().getCode());
                        mtWhoutitem.setGoodsName(detailsBean.getGoods().getName());
                        mtWhoutitem.setBaseunitId(detailsBean.getGoods().getBaseUnit().getId());
                        mtWhoutitem.setBaseunitName(detailsBean.getGoods().getBaseUnit().getName());
                        mtWhoutitem.setBizunit(detailsBean.getBizUnit());
                        mtWhoutitem.setAmount(new BigDecimal(detailsBean.getAmount()));
                        mtWhoutitem.setPrice(new BigDecimal(detailsBean.getPrice()));
                        mtWhoutitem.setMoney(new BigDecimal(detailsBean.getMoney()));
                        mtWhoutitem.setTaxrate(new BigDecimal(detailsBean.getTaxRate()));
                        mtWhoutitem.setNotaxprice(new BigDecimal(detailsBean.getNoTaxPrice()));
                        mtWhoutitem.setNotaxmoney(new BigDecimal(detailsBean.getNoTaxMoney()));
                        mtWhoutitem.setTax(new BigDecimal(detailsBean.getTax()));
                        mtWhoutitem.setDiffmoney(new BigDecimal(detailsBean.getDiffMoney()));
                        mtWhoutitem.setStockprice(new BigDecimal(detailsBean.getStockPrice()));
                        mtWhoutitem.setStockmoney(new BigDecimal(detailsBean.getStockMoney()));
                        mtWhoutitem.setBizunitamount(new BigDecimal(detailsBean.getBizUnitAmount()));
                        mtWhoutitem.setBizunitprice(new BigDecimal(detailsBean.getBizUnitPrice()));
                        mtWhoutitem.setBizunitnotaxprice(new BigDecimal(detailsBean.getBizUnitNoTaxPrice()));
                        mtWhoutitem.setBizunitstockprice(new BigDecimal(detailsBean.getBizUnitStockPrice()));
                        mtWhoutitem.setStatus(1);
                        mtWhoutitemService.insertMtWhoutitem(mtWhoutitem);
                    }
                }
            } else {
                log.info("调用失败");
            }
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }
    }

    //消耗主表
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void getCost(MtShop shop, Long timeBegin, Long timeEnd, MtToken mtToken) throws Exception {
        Integer pageNo = 1;
        Integer pageSize = 200;
//        HashMap<String, Long> snIdList = new HashMap<>();//保存出库单id与美团出库单主表编号的对应关系，获取明细时需要写入

        SysDept sysDept = sysDeptService.selectDeptById(shop.getDeptId());

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        FoodConsumptionRequest foodConsumptionRequest = new FoodConsumptionRequest();
        foodConsumptionRequest.setOrgId(shop.getMtOrgid());
        foodConsumptionRequest.setStartTime(timeBegin);
        foodConsumptionRequest.setEndTime(timeEnd);
//        foodConsumptionRequest.setStatus(3);
        foodConsumptionRequest.setPage(new FoodConsumptionRequest.Page(pageNo, pageSize));

        MeituanResponse<FoodConsumptionResponse> response = meituanClient.invokeApi(foodConsumptionRequest, mtToken.getAccesstoken());
        log.info("response: " + response.toString());
        if (response.isSuccess()) {
            FoodConsumptionResponse resp = response.getData();

            if (resp.getItems().size() == 0) {
                return;
            }
            //插入数据
            for (FoodConsumptionResponse.ItemsBean itemsBean : resp.getItems()) {
                if (itemsBean.getStatus().getId() != 3) {
                    throw new CustomException("消耗单未完成出库！");
                }
                MtFoodconsum mtFoodconsum = new MtFoodconsum();
                mtFoodconsum.setFoodconsumptionsn(itemsBean.getItemSn());
                List<MtFoodconsum> mtFoodconsumList = mtFoodconsumService.selectMtFoodconsumList(mtFoodconsum);
                if (mtFoodconsumList.size() > 0) continue;

                mtFoodconsum.setMtShopld(shop.getId());
                mtFoodconsum.setMtOrgid(Long.valueOf(itemsBean.getOrgId()));
                mtFoodconsum.setMtOrgname(shop.getName());

                mtFoodconsum.setMtRootorgid(Long.valueOf(itemsBean.getRootOrgId()));
                mtFoodconsum.setOrgId(shop.getOrgId());
                mtFoodconsum.setOrgName(shop.getOrgName());
                mtFoodconsum.setFoodconsumptionsn(itemsBean.getItemSn());
                mtFoodconsum.setBiztime(itemsBean.getBizDate());
                mtFoodconsum.setMtStatus(3);
                mtFoodconsum.setOrderstarttimegte(itemsBean.getOrderStartTimeGTE());
                mtFoodconsum.setOrderendtimelte(itemsBean.getOrderEndTimeLTE());
                mtFoodconsum.setVersion(itemsBean.getVersion());
                mtFoodconsum.setDepartmentguid(sysDept.getGuid());
                mtFoodconsum.setStatus(1);
                mtFoodconsum.setCreateBy(shop.getSysuserid());
                mtFoodconsumService.insertMtFoodconsum(mtFoodconsum);

//                    snIdList.put(itemsBean.getItemSn(), mtFoodconsum.getId());
                //TODO 明细处理
                getCostItem(shop, mtToken, itemsBean.getItemSn(), mtFoodconsum.getId());
            }

            //分页未查询完，继续查询
            if (resp.getItems().size() - pageSize == 0) {
                pageNo++;
                this.getCost(shop, timeBegin, timeEnd, mtToken);
            }
        } else {
            log.info("调用失败");
        }
    }

    //消耗明细
    public void getCostItem(MtShop shop, MtToken mtToken, String sn, Long sumId) {
        SysDept sysDept = sysDeptService.selectDeptById(shop.getDeptId());

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        FoodConsumptionItemRequest foodConsumptionItemRequest = new FoodConsumptionItemRequest();
        foodConsumptionItemRequest.setOrgId(shop.getMtOrgid());
        foodConsumptionItemRequest.setItemSn(sn);
        foodConsumptionItemRequest.setConsumptionType(1);

        try {
            MeituanResponse<FoodConsumptionItemResponse> response = meituanClient.invokeApi(foodConsumptionItemRequest, mtToken.getAccesstoken());
            log.info("response: " + response.toString());
            if (response.isSuccess()) {
                FoodConsumptionItemResponse resp = response.getData();

                //插入数据
                for (FoodConsumptionItemResponse.DetailsBean bean : resp.getDetails()) {
                    BigDecimal outAmount = new BigDecimal(bean.getOutAmount());
                    BigDecimal notOutAmount = new BigDecimal(bean.getNotOutAmount());
                    if (outAmount.add(notOutAmount).compareTo(BigDecimal.ZERO) == 0) {
                        continue;
                    }
                    List<FoodConsumptionItemResponse.DetailsBean.GoodsDetailsBean> detailsBeans = bean.getGoodsDetails();
                    MtFoodconsumitem mtFoodconsumitem = new MtFoodconsumitem();
                    mtFoodconsumitem.setMtFoodconsumid(sumId);
                    mtFoodconsumitem.setFoodskuid(bean.getFoodSkuId());
                    mtFoodconsumitem.setFoodname(bean.getFoodName());
                    mtFoodconsumitem.setFoodspec(bean.getFoodSpec());
                    mtFoodconsumitem.setOutamount(bean.getOutAmount());
                    mtFoodconsumitem.setNotoutamount(bean.getNotOutAmount());
                    mtFoodconsumitem.setDepartmentguid(sysDept.getGuid());
                    mtFoodconsumitem.setCustomerId(shop.getCustomerId());
                    mtFoodconsumitem.setCustomerName(shop.getCustomerName());
                    mtFoodconsumitemService.insertMtFoodconsumitem(mtFoodconsumitem);


                    for (int i = 0; i < detailsBeans.size(); i++) {
                        FoodConsumptionItemResponse.DetailsBean.GoodsDetailsBean detailsBean = detailsBeans.get(i);
                        MtFoodconsumgoodsitem mtFoodconsumgoodsitem = new MtFoodconsumgoodsitem();
                        mtFoodconsumgoodsitem.setMtFoodconsumitemid(mtFoodconsumitem.getId());
//                        mtFoodconsumgoodsitem.setFoodskuid(detailsBean.getGoods().getId());
                        mtFoodconsumgoodsitem.setFoodname(bean.getFoodName());
                        mtFoodconsumgoodsitem.setFoodspec(bean.getFoodSpec());
                        mtFoodconsumgoodsitem.setMtWhCode(detailsBean.getWarehouse().getCode());
                        mtFoodconsumgoodsitem.setMtGoodsCode(detailsBean.getGoods().getCode());
                        mtFoodconsumgoodsitem.setMtGoodsName(detailsBean.getGoods().getName());
                        mtFoodconsumgoodsitem.setBaseunitId(detailsBean.getGoods().getBaseUnit().getId());
                        mtFoodconsumgoodsitem.setBaseunitName(detailsBean.getGoods().getBaseUnit().getName());
                        mtFoodconsumgoodsitem.setConsumptionamount(new BigDecimal(detailsBean.getConsumptionAmount()));
                        mtFoodconsumgoodsitem.setOutamount(detailsBean.getOutAmount());
                        mtFoodconsumgoodsitem.setBizunitconsamount(detailsBean.getBizUnitConsumptionAmount());
                        mtFoodconsumgoodsitem.setBizunitoutamount(detailsBean.getBizUnitOutAmount());
                        mtFoodconsumgoodsitem.setBizunitnotoutamount(detailsBean.getBizUnitNotOutAmount());
                        mtFoodconsumgoodsitem.setConversionratedesc(detailsBean.getConversionRateDesc());
                        mtFoodconsumgoodsitem.setSuppunitconsamount(new BigDecimal(StringUtils.isBlank(detailsBean.getSupplementaryUnitConsumptionAmount()) ? "0" : detailsBean.getSupplementaryUnitConsumptionAmount()));
                        mtFoodconsumgoodsitem.setSuppunitoutamount(new BigDecimal(StringUtils.isBlank(detailsBean.getSupplementaryUnitOutAmount()) ? "0" : detailsBean.getSupplementaryUnitConsumptionAmount()));
                        mtFoodconsumgoodsitem.setSuppunitnotoutamount(new BigDecimal((StringUtils.isBlank(detailsBean.getSupplementaryUnitNotOutAmount()) ? "0" : detailsBean.getSupplementaryUnitConsumptionAmount())));
                        mtFoodconsumgoodsitemService.insertMtFoodconsumgoodsitem(mtFoodconsumgoodsitem);
                    }
                }
            } else {
                log.info("调用失败");
            }
        } catch (MtSdkException e) {
            throw new CustomException(e.getErrMsg());
        }

    }

    //消耗物料明细
    public Object getCostGoodItem(Object obj) {

        return new Object();
    }

    //销售主表
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void getSale(MtShop shop, Long timeBegin, Long timeEnd, MtToken mtToken) throws Exception {
        Integer pageNo = 1;
        Integer pageSize = 200;

        MeituanClient meituanClient = mtConfig.getInstanceClient();
        DishSaleRequest dishSaleRequest = new DishSaleRequest();
        dishSaleRequest.setOrgId(shop.getMtOrgid());
        dishSaleRequest.setStartDate(timeBegin);
        dishSaleRequest.setEndDate(timeEnd);
        dishSaleRequest.setPageNo(pageNo);
        dishSaleRequest.setPageSize(pageSize);

        MeituanResponse<DishSaleResponse> response = meituanClient.invokeApi(dishSaleRequest, mtToken.getAccesstoken());
        log.info("response: " + response.toString());
        if (response.isSuccess()) {
            DishSaleResponse resp = response.getData();

            //插入数据
            for (DishSaleResponse.ItemsBean bean : resp.getItems()) {

                MtSales mtSales = new MtSales();
                mtSales.setDishname(bean.getDishName());
                mtSales.setBiztime(timeBegin);
                MtSales salesQuery = iMtSalesService.selectMtSalesByDishName(mtSales);
                if (salesQuery != null){
                    continue;
                }

                mtSales.setMtShopid(shop.getId());
                mtSales.setMtOrgid(shop.getMtOrgid());
                mtSales.setOrgId(shop.getOrgId());
                mtSales.setOrgName(shop.getOrgName());
                mtSales.setPoiname(bean.getPoiName());
                mtSales.setMerchantno(bean.getMerchantNo() + "");
                mtSales.setOrdertypename(bean.getOrderTypeName());
                mtSales.setDishcatename(bean.getDishCateName());
                mtSales.setSecondcatename(bean.getSecondCateName());
                mtSales.setDishid(bean.getDishId());
                mtSales.setSkuid(bean.getSkuId());
                mtSales.setDishspec(bean.getDishSpec());
                mtSales.setDishunitname(bean.getDishUnitName());
                mtSales.setDishsalecnt(bean.getDishSaleCnt());
                mtSales.setDishsaleamt(bean.getDishSaleAmt()==null?BigDecimal.ZERO:bean.getDishSaleAmt().divide(new BigDecimal(100)));
                mtSales.setDishcmpgnamt(bean.getDishCmpgnAmt()==null?BigDecimal.ZERO:bean.getDishCmpgnAmt().divide(new BigDecimal(100)));
                mtSales.setDishincomeamt(bean.getDishIncomeAmt()==null?BigDecimal.ZERO:bean.getDishIncomeAmt().divide(new BigDecimal(100)));
                mtSales.setTaxamt(bean.getTaxAmt()==null?BigDecimal.ZERO:bean.getTaxAmt().divide(new BigDecimal(100)));
                mtSales.setNotaxincomeamt(bean.getNoTaxIncomeAmt()==null?BigDecimal.ZERO:bean.getNoTaxIncomeAmt().divide(new BigDecimal(100)));
                mtSales.setCustomerid(shop.getCustomerId());
                mtSales.setCustomername(shop.getCustomerName());
                mtSales.setDeptId(shop.getDeptId());
                mtSales.setDeptName(shop.getDeptName());
                mtSales.setStatus(1);
                mtSales.setBiztime(timeBegin);
                mtSales.setCreateBy(shop.getSysuserid());
                iMtSalesService.insertMtSales(mtSales);
            }

            //分页未查询完，继续查询
            if (resp.getPage().getTotalPageSize() - pageNo > 0) {
                pageNo++;
                this.getSale(shop, timeBegin, timeEnd, mtToken);
            }
        } else {
            log.info("调用失败");
        }
    }
}
